package cn.gson.crm.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.gson.crm.model.dao.BackRecordDAO;
import cn.gson.crm.model.dao.ConstactOrderDAO;
import cn.gson.crm.model.pojo.Backrecord;
import cn.gson.crm.model.pojo.ConstactOrder;
import cn.gson.crm.model.vo.BackRecordVO;
import cn.gson.crm.model.vo.ConstactOrderVO;

@Service
@Transactional
public class BackRecordService {
	@Autowired
	private BackRecordDAO bDao;
	@Autowired
	private ConstactOrderDAO cDao;

	/**
	 * 获取所有回款记录
	 * 
	 * @param page
	 * @param rows
	 * @return
	 */
	public List<BackRecordVO> getAllBackRecord(int page, int rows) {
		PageRequest pRequest = new PageRequest(page - 1, rows);
		List<Backrecord> listpo = bDao.getAllBackRecord(pRequest);
		List<BackRecordVO> listvo = new ArrayList<>();
		for (Backrecord backrecord : listpo) {
			listvo.add(returnBackRecordVO(backrecord));
		}
		return listvo;
	}

	public BackRecordVO returnBackRecordVO(Backrecord b) {
		BackRecordVO bVo = new BackRecordVO(b.getBrId(), b.getBrCoId(), b.getBrCoName(), b.getBrIfTicket(),
				b.getBrMoney(), b.getBrOwner(), b.getBrPayWay(), b.getBrPeriod(), b.getBrRemarks(), b.getBrTime());
		ConstactOrder cOrder = b.getConstactOrder();
		if (cOrder != null) {
			ConstactOrderVO cVo = new ConstactOrderVO(cOrder.getCoId(), cOrder.getCoTheme());
			bVo.setCoIdvo(cVo.getCoId());
			bVo.setCoThemeVo(cVo.getCoTheme());
		}
		return bVo;
	}

	/**
	 * 添加回款记录
	 * 
	 * @param b
	 * @param coId
	 */
	public void addBackRecord(Backrecord b,Long coIdvo) {
		System.out.println(b.getBrId());
		try {
			ConstactOrder cOrder = cDao.findOne(coIdvo);
			b.setConstactOrder(cOrder);
			bDao.save(b);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	
	public void deleteBr(Long id) {
		try {
			bDao.delete(bDao.findOne(id));
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 编辑回款记录
	 * 
	 * @param b
	 * @param coId
	 *//*
	public void editRecord(Backrecord b,Long coIdd) {
		System.out.println(b.getBrId());
		try {
			ConstactOrder cOrder = cDao.findOne(Long.parseLong(b.getBrRemarks()));
			b.setBrRemarks(cOrder.getCoTheme());
			b.setConstactOrder(cOrder);
			b.setBrId(coIdd);
			bDao.save(b);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
*/

	
	
	/**
	 * 回款记录id查询
	 */
	public BackRecordVO getOrderById(Long id) {
		Backrecord cOrder = bDao.findById(id);
		return returnBackRecordVO(cOrder);
	}

	public Long count() {
		return bDao.count();
	}
}
